package com.linwankaifa.linwancunyi.ui.patient;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.linwankaifa.linwancunyi.R;
import com.linwankaifa.linwancunyi.bean.DoctorBean;
import com.linwankaifa.linwancunyi.bean.HuatiBean;
import com.linwankaifa.linwancunyi.ui.adapter.FragmentAdapter;
import com.linwankaifa.linwancunyi.ui.login.LoginChooseCharcater;
import com.linwankaifa.linwancunyi.util.BottomNavigationViewHelper;
import com.linwankaifa.linwancunyi.util.Data_whole;
import com.linwankaifa.linwancunyi.util.JsonTransformation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.widget.Toast.makeText;


public class PatientMain extends FragmentActivity
        implements PatientArticle.OnFragmentInteractionListener, PatientConsult.OnFragmentInteractionListener, PatientFunction.OnFragmentInteractionListener, PatientPersonal.OnFragmentInteractionListener {
    ArrayList<Fragment> viewlist = new ArrayList<>();
    PatientArticle patientArticle;
    PatientFunction patientFunction;
    PatientPersonal patientPersonal;
    PatientConsult patientConsult;
    String SHAREDPREFERENCES_NAME = "shared.xml";
    SharedPreferences preferences;
    private ViewPager viewPager;
    private MenuItem menuItem;
    private BottomNavigationView bottomNavigationView;
    private List<DoctorBean> doctors = new ArrayList<DoctorBean>();
    private List<HuatiBean> huati = new ArrayList<HuatiBean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_main);
        preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        //默认 >3 的选中效果会影响ViewPager的滑动切换时的效果，故利用反射去掉
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.navigation_home:
                                viewPager.setCurrentItem(0);
                                break;
                            case R.id.navigation_artile:
                                viewPager.setCurrentItem(1);
                                break;
                            case R.id.navigation_consult:
                                viewPager.setCurrentItem(2);
                                break;
                            case R.id.navigation_personal:
                                viewPager.setCurrentItem(3);
                                break;
                        }
                        return false;
                    }
                });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                menuItem = bottomNavigationView.getMenu().getItem(position);
                menuItem.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        //禁止ViewPager滑动
//        viewPager.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return true;
//            }
//        });
        patientArticle = new PatientArticle();
        patientConsult = new PatientConsult();
        patientFunction = new PatientFunction();
        patientPersonal = new PatientPersonal();

        viewlist.add(patientFunction);
        viewlist.add(patientArticle);
        viewlist.add(patientConsult);
        viewlist.add(patientPersonal);

        setupViewPager(viewPager);
        getArticle();
        getDoctors();


    }

    private void setupViewPager(ViewPager viewPager) {
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), viewlist);
        viewPager.setAdapter(fragmentAdapter);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    public void doctor_topic(View view) {
        viewPager.setCurrentItem(1);
    }

    public void quick_question(View view) {
        Intent intent = new Intent(PatientMain.this, PatientQuickQuestion.class);
        startActivity(intent);
    }

    public void find_doctor(View view) {
        Intent intent = new Intent(PatientMain.this, PatientFindDoctor.class);
        startActivity(intent);
    }

    //症状自诊
    public void patient_sdos(View view) {
        Intent intent = new Intent(PatientMain.this, PatientSDOS.class);
        startActivity(intent);
    }

    public void find_hospital(View view) {
        Intent intent = new Intent(PatientMain.this, PatientFindHospital.class);
        startActivity(intent);
    }

    //健康评测
    public void health_test(View view) {
        Intent intent = new Intent(PatientMain.this, PatientHealthTest.class);
        startActivity(intent);
    }

    public void health_card(View view) {
        Intent intent = new Intent(PatientMain.this, PatientHealthCard.class);
        startActivity(intent);
    }

    public void setup_and_help(View view) {
        Intent intent = new Intent(PatientMain.this, PatientSetupAndHelp.class);
        startActivity(intent);
    }

    public void enter_topic(View view) {
        Intent intent = new Intent(PatientMain.this, PatientArticle_content.class);
        startActivity(intent);
    }

    public void quit(View view) {
        Intent intent = new Intent(PatientMain.this, LoginChooseCharcater.class);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("token", "");
        editor.commit();
        startActivity(intent);
    }


    public void getDoctors() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                JsonTransformation.objectToJson(Data_whole.getPatientBean()));

        String url = getString(R.string.url)+"/";
        url += "patient/getchateddoctors";

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 如果失败，就显示失败信息
                Toast toast = makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 判断请求是否成功
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess.equals("404"))
                            makeText(getApplicationContext(), "错误请求404", Toast.LENGTH_SHORT).show();
                        else {
                            List<DoctorBean> doctorList = JsonTransformation.jsonToList(isSuccess, DoctorBean.class);
                            for (DoctorBean doctor : doctorList)
                                doctors.add(doctor);
                            patientConsult.setdoctorList(doctors);
                        }
                    }
                });
            }
        });
    }

    public void getArticle() {
        OkHttpClient client = new OkHttpClient();
        String url = getString(R.string.url)+"/patient/getarticleinfoList";
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 如果失败，就显示失败信息
                Toast toast = makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 判断请求是否成功
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess.equals("404"))
                            makeText(getApplicationContext(), "错误请求404", Toast.LENGTH_SHORT).show();
                        else {
                            List<HuatiBean> articleList = JsonTransformation.jsonToList(isSuccess, HuatiBean.class);
                            huati.addAll(articleList);
                            patientArticle.setarticleList(huati);
                            patientArticle.initlist();
                        }
                    }
                });
            }
        });
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK) {

            Intent home = new Intent(Intent.ACTION_MAIN);

            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            home.addCategory(Intent.CATEGORY_HOME);

            startActivity(home);

            return true;

        }

        return super.onKeyDown(keyCode, event);

    }


    public void patient_info(View view) {
        Intent intent = new Intent(PatientMain.this, PatientOwnInformation.class);
        startActivity(intent);
    }
}
